package com.high.school.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.high.school.model.User;
import com.high.school.validator.UserValidator;


@Controller
public class FormController {

	@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserValidator());
    }
	
	@RequestMapping("form")
	public ModelAndView showForm() {
		User user = new User();
		ModelAndView model = new ModelAndView();
		model.addObject("user", user);
		return model;
	}

	
	@RequestMapping(value = "form", method = RequestMethod.POST)
	public String getInfo(Model model, @Valid User user, BindingResult result) {
		
		if(result.hasErrors()){
			return "form";
		}else{
			model.addAttribute("user", user);
			return "form";
		}
		
	}

}
